package com.lysj.bhp.wallet.controller;

import com.lysj.bhp.wallet.base.WalletContent;
import com.lysj.bhp.wallet.domain.BhpcWallet;
import com.lysj.bhp.system.base.BaseConst;
import com.lysj.bhp.util.web.ParamUtil;
import com.lysj.bhp.util.web.Resp;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.web3j.crypto.WalletUtils;

import java.io.File;
import java.math.BigDecimal;

@RestController
@RequestMapping("/bhpc_wallet")
public class BhpcWalletController extends WalletContent {

    private Logger logger = LoggerFactory.getLogger(EthereumWalletController.class);


    @ApiOperation(value = "获取一个BHPC钱包", notes = "一个账号只能创建一个钱包")
    @PostMapping("/my_bhpc_wallet")
    public Resp myBhpcWallet() throws Exception {
        BhpcWallet bhpcWalletQuery = bhpcWalletRepository.findByUserId(currentUser().getUserId());
        if (bhpcWalletQuery != null) {
            return new Resp(Resp.SUCCESS, "您已经有一个BHPC钱包了,请不要重复创建", "0x" + bhpcWalletQuery.getAddress());
        }
        String password = ParamUtil.uuid();
        String keystoreFilename = WalletUtils.generateFullNewWalletFile(password, new File(BaseConst.KEY_STORE_DIR));

        String[] addressArray = keystoreFilename.split("--");
        String address = addressArray[2].substring(0, 40);

        BhpcWallet bhpcWallet = new BhpcWallet();
        bhpcWallet.setKeystore(keystoreFilename);
        bhpcWallet.setPassword(password);
        bhpcWallet.setUserId(currentUser().getUserId());
        bhpcWallet.setAddress(address);
        bhpcWallet.setBalance(BigDecimal.ZERO);
        bhpcWallet.setFreezeBalance(BigDecimal.ZERO);
        bhpcWallet.setAvailBalance(BigDecimal.ZERO);
        bhpcWallet.setBookKeepBalance(BigDecimal.ZERO);
        //------------增加钱包的抵押冻结资产----------------
        bhpcWallet.setPledgeFreezeBalance(BigDecimal.ZERO);
        logger.info(bhpcWallet.toString());
        bhpcWalletRepository.save(bhpcWallet);
        return new Resp(Resp.SUCCESS, "创建BHPC币钱包成功", "0x" + bhpcWallet.getAddress());
    }


}
